package com.chen.ssm.web;


import com.chen.ssm.entity.*;
import com.chen.ssm.service.FlightService;
import com.chen.ssm.service.TicketOrderService;
import com.chen.ssm.service.UserService;
import com.chen.ssm.util.CookiesUtil;
import com.chen.ssm.util.JsonDateValueProcessor;
import com.chen.ssm.util.ResponseUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * com.chen.ssm.web
 * 作者      : 金博超
 * 描述      :
 * 创建日期  : 2020/11/11
 * 修改日期  :
 */
@Controller
@RequestMapping("/user")
public class UserController {

  @Resource
  private UserService userService;

  @Resource
  private TicketOrderService ticketOrderService;


  @Resource
  private FlightService flightService;

  private User user;
  private Integer currentUserId;
  private static Integer login_times ;
  private List<Ticketorder> ticketorderList;
  private CookiesUtil cookiesUtil = new CookiesUtil();
  private String cookieName = "token";
  private String format = "yyyy-MM-dd HH:mm:ss";


  @RequestMapping("/test")
  public String test() {
    return "list";
  }

  @RequestMapping("/index")
  public String index() {
    return "login";
  }

  @RequestMapping("/login3")
  public String login(User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
    user = userService.login(user);
    JSONObject result = new JSONObject();
    boolean flag = false;

    login_times = (Integer) request.getSession().getAttribute("login_times");
    if (user != null) {
      request.getSession().setAttribute("currentUser", user.getUsername());
      setCurrentUserId(user.getId());
      cookiesUtil.addcookie("token", user.getUsername(), 1800, response);
      flag = true;
    } else if(login_times<=3){
//      request.getSession().setAttribute("message", "用户名或密！！！");

      request.getSession().setAttribute("login_times",login_times++);
      System.out.println(user.getUsername());
    }else {
      request.getSession().setAttribute("message", "尝试三次，请两小时后尝试");
      System.out.println(user.getUsername());
    }
    result.put("success", flag);
    ResponseUtil.write(response, result);
    return "main";
  }

  @RequestMapping("/showUserInfo")
  public String showUserInfo(HttpServletRequest request) {
    HttpSession session = request.getSession();
    Integer currentUserId = getCurrentUserId();
    User userById = userService.getUserById(currentUserId);
    session.setAttribute("user", userById);
    request.setAttribute("mainPage", "userCenter/userInfo.jsp");
    return "main_userCenter";
  }

  @RequestMapping("/save")
  public String save(User user, HttpServletResponse response, HttpServletRequest request) throws Exception {
    System.out.println("user----save-----");
    JSONObject result = new JSONObject();
    String id = request.getParameter("id");
    boolean flag = false;
    Integer i;
    List<User> list = userService.getUserList(user);
    if(user.getUsername()==null||user.getPassword()==null){
      request.getSession().setAttribute("message", "用户名密码不能为空");
      System.out.println("用户名密码不能为空");
      return null;
    }
    if(list.size()!=0){
      request.getSession().setAttribute("message", "该用户已存在，请更改用户名");
      System.out.println("该用户已存在，请更改用户名");
      return null;
    }else if (user.getUsername().length()<6|| user.getUsername().length()>15){
      request.getSession().setAttribute("message", "用户名长度不规范");
      System.out.println("用户名长度不规范");
      return null;
    }
    else if (user.getPassword().length()<6 || user.getPassword().length()>10){
      request.getSession().setAttribute("message", "密码长度不规范");
      System.out.println("密码长度不规范");
      return null;
    }else {
      if (id == null) {//添加操作
        i = userService.insertSelective(user);
      } else {//修改操作
        i = userService.updateByPrimaryKeySelective(user);
      }
      if (i > 0) {
        flag = true;
      }
    }
    System.out.println("用户注册成功");
    result.put("success", flag);
    ResponseUtil.write(response, result);
    return null;
  }

  @RequestMapping("/deleteUser")
  public String deleteUser(HttpServletResponse response, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    String[] split = ids.split(",");
    JSONObject result = new JSONObject();
    String message = "用户有订单,不能进行删除操作！";
    String userID = "";
    boolean flag = false;
    int count = 0;
    try {
      for (String i : split) {
        ticketorderList = ticketOrderService.selectListByUserId(Integer.parseInt(i));
        if (ticketorderList.size() > 0) {
          userID = userID + i + ",";
          continue;
        } else {
          Integer integer = userService.deleteByPrimaryKey(Integer.parseInt(i));
          count++;
        }
      }
      if (count == split.length) {
        flag = true;
        message = "数据已成功删除！";
      } else {
        message = "用户id为" + userID.substring(0, userID.length() - 1) + message;
      }
      result.put("success", flag);
      result.put("message", message);
      ResponseUtil.write(response, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


  @RequestMapping("/userCenter")
  public String userCenter() {
    return "main_userCenter";
  }


  @RequestMapping("/logout")
  public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
    JSONObject result = new JSONObject();
    HttpSession session = request.getSession();
    session.removeAttribute("currentUser");
    session.invalidate();
    cookiesUtil.deleteCookies(cookieName,request, response);
    result.put("success", true);
    ResponseUtil.write(response, result);
    return "main";
  }

  @RequestMapping("/adminManagerPage")
  public String managerList() {
    return "admin/userManage";
  }







  //获取用户的订单
  @RequestMapping("/userTickOrderList")
  public String userTickOrderList(HttpServletRequest request, User user, HttpServletResponse response) {
    PageBean pageBean = new PageBean();
    JSONObject result = new JSONObject();
    String page = request.getParameter("page");
    String rows = request.getParameter("rows");
    if (rows != null) {
      pageBean.setPageSize(Integer.parseInt(rows));
      user.setPageSize(pageBean.getPageSize());
    }
    if (page != null) {
      pageBean.setPage(Integer.parseInt(page));
      user.setPage(pageBean.getStart());
    }
    try {
      Integer count = ticketOrderService.getTKCount(user);
      List<Ticketorder> aircraftList = ticketOrderService.getListByUser(user);
      JsonConfig jsonConfig = new JsonConfig();
      List<Flight> flightList = new ArrayList<Flight>();
      Set<Integer> st = new HashSet<Integer>();
      for(Ticketorder tk:aircraftList){
        st.add(tk.getFlightid());
      }
      for (Integer it: st){
        flightList.add(flightService.selectByPrimaryKey(it));
      }
      jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor(format));
      JSONArray array = JSONArray.fromObject(flightList, jsonConfig);
      result.put("rows", array);
      result.put("total", count);
      ResponseUtil.write(response, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  @RequestMapping("/comboList")
  public String comboList(HttpServletResponse response) {
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id", "");
    jsonObject.put("username", "请选择...");
    jsonArray.add(jsonObject);
    List<User> userList = userService.getUserList(user);
    JsonConfig jsonConfig = new JsonConfig();
    JSONArray rows = JSONArray.fromObject(userList, jsonConfig);
    jsonArray.addAll(rows);
    ResponseUtil.write(response, jsonArray);
    return null;
  }






  @RequestMapping("/search")
  public String search() {
    return "login";
  }

  public Integer getCurrentUserId() {
    return currentUserId;
  }

  public void setCurrentUserId(Integer currentUserId) {
    this.currentUserId = currentUserId;
  }
}
